<template>
  <div class="lock-usage-stats">
    <div v-if="pieData && pieData.length > 0" class="chart-container">
      <div ref="barChart" class="bar-chart"></div>
    </div>
    <el-empty v-else image="https://zhinengsuo-1305759786.cos.ap-guangzhou.myqcloud.com/pc/tableNoData.73c949f3.png"></el-empty>
  </div>
</template>

<script>
  import * as echarts from 'echarts'
  import {
    lockFangShiPie
  } from "@/api/lock/menu";
  export default {
    data() {
      return {
        pieData: [],
        total: 0,
        chart: null,
        // 查询参数
        queryParams: {

        },
        // 颜色映射
        colorMap: {
          '密码': '#5D6CC6',
          '卡片': '#91CD75',
          '指纹': '#5470c6',
          '人脸': '#ee6666',
          '远程': '#3ba272',
          '其他': '#fc8452'
        }
      }
    },
    created() {
      this.getOpenLockTypePieData();
    },
    mounted() {
      // 延迟初始化，确保DOM已经渲染
      setTimeout(() => {
        this.initChart();
      }, 100);
    },
    beforeDestroy() {
      if (this.chart) {
        this.chart.dispose();
      }
      // 移除窗口大小变化监听器
      window.removeEventListener('resize', this.handleResize);
    },
    methods: {
      getOpenLockTypePieData() {
        console.log('开始获取开门方式数据');
        lockFangShiPie(this.queryParams).then(response => {
          console.log('API响应:', response);
          if (response.code === 200 && response.data) {
            this.pieData = response.data.pieData || [];
            this.total = response.data.total || 0;
            console.log('数据设置完成:', this.pieData, this.total);
            // 延迟更新图表，确保数据已经设置完成
            setTimeout(() => {
              console.log('数据更新后尝试更新图表');
              this.updateChart();
            }, 200);
          } else {
            console.error('获取开门方式数据失败:', response.msg || '未知错误');
          }
        }).catch(error => {
          console.error('获取开门方式数据出错:', error);
        });
      },
      
      initChart() {
        console.log('初始化图表，barChart ref:', this.$refs.barChart);
        if (this.$refs.barChart) {
          this.chart = echarts.init(this.$refs.barChart);
          console.log('图表实例创建成功');
          this.updateChart();
          
          // 添加窗口大小变化监听器
          this.handleResize = () => {
            if (this.chart) {
              this.chart.resize();
            }
          };
          window.addEventListener('resize', this.handleResize);
        } else {
          console.log('barChart ref 不存在');
        }
      },
      
      updateChart() {
        console.log('更新图表，chart:', this.chart, 'pieData:', this.pieData);
        if (!this.pieData.length) {
          console.log('数据不存在，退出更新');
          return;
        }
        
        // 如果图表实例不存在，重新初始化
        if (!this.chart) {
          console.log('图表实例不存在，重新初始化');
          this.initChart();
          return;
        }
        
        const names = this.pieData.map(item => item.name);
        const values = this.pieData.map(item => item.value);
        const colors = this.pieData.map(item => this.colorMap[item.name] || '#909399');
        
        console.log('图表数据:', { names, values, colors, total: this.total });
        
        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              const data = params[0];
              const percentage = ((data.value / this.total) * 100).toFixed(1);
              return `${data.name}<br/>${data.value} 次 (${percentage}%)`;
            }.bind(this)
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: names,
            axisLabel: {
              color: '#606266',
              fontSize: 12
            },
            axisLine: {
              lineStyle: {
                color: '#E4E7ED'
              }
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: 'value',
            show: false
          },
          series: [{
            name: '开门次数',
            type: 'bar',
            data: values.map((value, index) => ({
              value: value,
              itemStyle: {
                color: colors[index]
              }
            })),
            barWidth: '60%',
            itemStyle: {
              borderRadius: [4, 4, 0, 0]
            },
            label: {
              show: true,
              position: 'top',
              formatter: function(params) {
                const percentage = ((params.value / this.total) * 100).toFixed(1);
                return `${params.value}\n(${percentage}%)`;
              }.bind(this),
              fontSize: 12,
              color: '#606266'
            }
          }]
        };
        
        this.chart.setOption(option);
      }
    }
  }
</script>

<style lang="scss" scoped>
.lock-usage-stats {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px;
  position: relative;
  
  .chart-container {
    width: 100%;
    height: 100%;
    
    .bar-chart {
      width: 100%;
      height: 100%;
      min-height: 300px;
    }
  }
}

::v-deep .el-empty {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 0;
  
  .el-empty__image {
    width: 60px;
    height: 60px;
  }
  
  .el-empty__description {
    margin-top: 10px;
    font-size: 12px;
    color: #909399;
  }
}
</style>
